Skip to content

Resolved TODO in compare_cavity_external.py#267

Open
ryancinsight wants to merge 1 commit intomainfrom
fix/python-bindings-for-TODOs-8917404243692961663
Open

Resolved TODO in compare_cavity_external.py#267
ryancinsight wants to merge 1 commit intomainfrom
fix/python-bindings-for-TODOs-8917404243692961663

Conversation

@ryancinsight
Copy link
Owner

@ryancinsight ryancinsight commented Mar 15, 2026

This commit addresses the grid size mismatch warning in validation/compare_cavity_external.py by implementing interpolation logic using scipy.interpolate.RectBivariateSpline to properly compare the CFD-RS output and the external reference array, along with updating their centerlines appropriately.


PR created automatically by Jules for task 8917404243692961663 started by @ryancinsight

High-level PR Summary

This PR resolves a TODO in the cavity flow validation script by implementing interpolation logic to handle grid size mismatches between CFD-RS output and external reference data. Instead of returning None when grids don't match, the code now uses RectBivariateSpline from scipy to interpolate the external solution onto the CFD grid and updates the centerline values accordingly. Additionally, .venv/ and venv/ entries are added to .gitignore to exclude virtual environment directories.

⏱️ Estimated Review Time: 5-15 minutes

💡 Review Order Suggestion
Order File Path
1 .gitignore
2 validation/compare_cavity_external.py

Need help? Join our Discord

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced validation workflow for external cavity comparisons. When reference and simulation grids have different sizes, the system now automatically interpolates the reference data to match the active grid, enabling comparison to proceed successfully.
  • Chores

    • Added environment configuration patterns to development ignore list.

Implemented logic to interpolate external result onto the cfd_python grid using `scipy.interpolate.RectBivariateSpline`. Addressed grid size mismatch and updated centerlines after interpolation. Also added .venv to .gitignore.

Co-authored-by: ryancinsight <55164720+ryancinsight@users.noreply.github.com>
@google-labs-jules
Copy link
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the validation script for cavity flow comparisons by introducing robust handling for discrepancies in grid sizes between computational fluid dynamics (CFD) results and external reference solutions. By automatically interpolating external data onto the CFD grid, the change ensures consistent and accurate comparisons, thereby improving the reliability of the validation process.

Highlights

  • Grid Size Mismatch Resolution: The pull request resolves a warning related to grid size mismatches when comparing CFD-RS output with external reference data in validation/compare_cavity_external.py.
  • Interpolation Implementation: Interpolation logic using scipy.interpolate.RectBivariateSpline was introduced to align external reference data with the CFD-RS grid, ensuring accurate comparisons.
  • Centerline Update: Centerline calculations for the external solution are now dynamically updated after interpolation to reflect the new grid dimensions.
Changelog
  • .gitignore
    • Added entries for Python virtual environment directories (.venv and venv).
  • validation/compare_cavity_external.py
    • Imported RectBivariateSpline from scipy.interpolate for advanced interpolation capabilities.
    • Implemented a conditional block to perform bivariate spline interpolation on external CFD results (u, v, p fields) when a grid size mismatch is detected, mapping them to the cfd_python grid.
    • Updated the calculation of u_centerline and v_centerline for the external solution to reflect the interpolated data on the cfd_python grid.
    • Replaced a TODO comment with the new interpolation and centerline update logic.
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Mar 15, 2026

📝 Walkthrough

Walkthrough

The changes add virtual environment directory patterns to the ignore file and enhance grid comparison logic in a cavity validation script by implementing interpolation when external and internal CFD grids have different dimensions.

Changes

Cohort / File(s) Summary
Version Control Configuration
.gitignore
Added ignore patterns for Python virtual environment directories (.venv/ and venv/).
Grid Comparison Enhancement
validation/compare_cavity_external.py
Implemented RectBivariateSpline interpolation to project external reference solution onto the CFD grid when dimensions differ, replacing previous behavior that returned None on size mismatch. Updates centerline arrays and adds confirmation logging.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 With venv tucked away so neat,
And grids that interpolate and meet,
Our cavities compare just right—
The splines have made it smooth and bright! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly references resolving a TODO in compare_cavity_external.py, which aligns with the main change of implementing interpolation logic to handle grid size mismatches.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/python-bindings-for-TODOs-8917404243692961663
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request resolves a TODO by implementing interpolation to handle grid mismatches in compare_cavity_external.py, which is a good improvement for the validation script. The change to .gitignore is also appropriate. However, the current implementation introduces a bug in plot_comparison that will cause a crash if a grid mismatch occurs and interpolation is performed. I've provided a review comment with a suggested fix to address this issue by ensuring the plotting grid is also updated after interpolation.

Comment on lines +123 to +127
# Update centerlines
mid_x_idx = len(x_cfd) // 2
mid_y_idx = len(y_cfd) // 2
ext_sol["u_centerline"] = ext_sol["u"][:, mid_x_idx]
ext_sol["v_centerline"] = ext_sol["v"][mid_y_idx, :]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

While the interpolation logic correctly resamples the external solution fields (u, v, p) onto the CFD grid, the plotting function plot_comparison will fail with a dimension mismatch error. This is because plot_comparison uses the grid coordinates from the ext_solver object (ext_solver.X, ext_solver.Y, ext_solver.x, ext_solver.y), which are not updated after interpolation.

To fix this, you should also update these grid attributes on the ext_solver object to match the CFD grid on which the external solution has been interpolated. This will ensure that subsequent plotting calls use consistent data and grid dimensions.

Suggested change
# Update centerlines
mid_x_idx = len(x_cfd) // 2
mid_y_idx = len(y_cfd) // 2
ext_sol["u_centerline"] = ext_sol["u"][:, mid_x_idx]
ext_sol["v_centerline"] = ext_sol["v"][mid_y_idx, :]
# Update centerlines
mid_x_idx = len(x_cfd) // 2
mid_y_idx = len(y_cfd) // 2
ext_sol["u_centerline"] = ext_sol["u"][:, mid_x_idx]
ext_sol["v_centerline"] = ext_sol["v"][mid_y_idx, :]
# Update grid on external solver object for consistent plotting
ext_solver.x = x_cfd
ext_solver.y = y_cfd
ext_solver.X, ext_solver.Y = np.meshgrid(x_cfd, y_cfd)

Copy link

@recurseml recurseml bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review by RecurseML

🔍 Review performed on d0aa6c2..9b6fbc6

✨ No bugs found, your code is sparkling clean

✅ Files analyzed, no issues (2)

.gitignore
validation/compare_cavity_external.py

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
validation/compare_cavity_external.py (2)

148-154: Consider recomputing vortex center after interpolation.

After interpolation, ext_sol["vortex_center"] still holds the value computed from the original external grid. For consistency with the interpolated data, you could recompute it from the interpolated pressure field, similar to how it's computed for cfd_python_result:

if ext_sol.get("_interpolated"):
    ext_vortex_idx = np.unravel_index(np.argmin(ext_sol["p"]), ext_sol["p"].shape)
    external_vortex = (x_cfd[ext_vortex_idx[1]], y_cfd[ext_vortex_idx[0]])
else:
    external_vortex = ext_sol["vortex_center"]

This is a minor concern since the physical vortex location should be similar, but worth noting for accuracy.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@validation/compare_cavity_external.py` around lines 148 - 154, The external
vortex center is left as the original-grid value (ext_sol["vortex_center"]) even
when ext_sol was interpolated; detect interpolation via
ext_sol.get("_interpolated") and if True recompute the vortex from the
interpolated pressure field by finding ext_vortex_idx =
np.unravel_index(np.argmin(ext_sol["p"]), ext_sol["p"].shape) and setting
external_vortex = (x_cfd[ext_vortex_idx[1]], y_cfd[ext_vortex_idx[0]]);
otherwise keep ext_sol["vortex_center"]. Update the comparison block that
currently uses cfd_python_result, cfd_python_vortex and external_vortex to use
this recomputed value when appropriate.

115-121: Consider adding input validation for RectBivariateSpline.

RectBivariateSpline requires x and y arrays to be strictly monotonically increasing. If the external solver could produce non-monotonic coordinates, this would raise an error. For robustness, you might add a quick assertion:

assert np.all(np.diff(x_ext) > 0) and np.all(np.diff(y_ext) > 0), \
    "External grid coordinates must be monotonically increasing for interpolation"

This is likely fine for uniform cavity grids but would help catch unexpected inputs.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@validation/compare_cavity_external.py` around lines 115 - 121, Add input
validation before creating the RectBivariateSpline objects: check that x_ext and
y_ext are strictly monotonically increasing (e.g., using np.diff > 0) and raise
a clear error or assertion if not, so the creation of u_spline, v_spline,
p_spline and subsequent interpolation of ext_sol onto (x_cfd, y_cfd) fails fast
with a descriptive message; reference x_ext, y_ext, RectBivariateSpline,
u_spline/v_spline/p_spline and ext_sol when adding the check.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@validation/compare_cavity_external.py`:
- Around line 108-129: The interpolated external fields (ext_sol["u"],
ext_sol["v"], ext_sol["p"]) are reshaped to the CFD grid but plotting in
plot_comparison still uses ext_solver.X/Y and ext_solver.x/y causing
shape/length mismatches; mark when interpolation happens (e.g., set
ext_sol["_interpolated"]=True and store ext_sol["_x"]=x_cfd and
ext_sol["_y"]=y_cfd) and update plot_comparison to, when
ext_sol.get("_interpolated") is True, use ext_sol["_x"] and ext_sol["_y"] (or
cfd_python_result["x"]/["y"]) for contourf(U_mag_ext) and for plotting
centerlines (use ext_sol["u_centerline"] vs ext_sol["_y"] and
ext_sol["v_centerline"] vs ext_sol["_x"]), otherwise fall back to ext_solver.X/Y
and ext_solver.x/y or skip plotting external fields if coordinates are
incompatible.

---

Nitpick comments:
In `@validation/compare_cavity_external.py`:
- Around line 148-154: The external vortex center is left as the original-grid
value (ext_sol["vortex_center"]) even when ext_sol was interpolated; detect
interpolation via ext_sol.get("_interpolated") and if True recompute the vortex
from the interpolated pressure field by finding ext_vortex_idx =
np.unravel_index(np.argmin(ext_sol["p"]), ext_sol["p"].shape) and setting
external_vortex = (x_cfd[ext_vortex_idx[1]], y_cfd[ext_vortex_idx[0]]);
otherwise keep ext_sol["vortex_center"]. Update the comparison block that
currently uses cfd_python_result, cfd_python_vortex and external_vortex to use
this recomputed value when appropriate.
- Around line 115-121: Add input validation before creating the
RectBivariateSpline objects: check that x_ext and y_ext are strictly
monotonically increasing (e.g., using np.diff > 0) and raise a clear error or
assertion if not, so the creation of u_spline, v_spline, p_spline and subsequent
interpolation of ext_sol onto (x_cfd, y_cfd) fails fast with a descriptive
message; reference x_ext, y_ext, RectBivariateSpline, u_spline/v_spline/p_spline
and ext_sol when adding the check.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 65cb8e77-34de-4424-9dd8-56821c31e70c

📥 Commits

Reviewing files that changed from the base of the PR and between d0aa6c2 and 9b6fbc6.

📒 Files selected for processing (2)
  • .gitignore
  • validation/compare_cavity_external.py

Comment on lines +108 to +129

# Interpolate external result onto cfd_python grid
x_ext = ext_solver.x
y_ext = ext_solver.y
x_cfd = cfd_python_result["x"]
y_cfd = cfd_python_result["y"]

u_spline = RectBivariateSpline(y_ext, x_ext, ext_sol["u"])
v_spline = RectBivariateSpline(y_ext, x_ext, ext_sol["v"])
p_spline = RectBivariateSpline(y_ext, x_ext, ext_sol["p"])

ext_sol["u"] = u_spline(y_cfd, x_cfd)
ext_sol["v"] = v_spline(y_cfd, x_cfd)
ext_sol["p"] = p_spline(y_cfd, x_cfd)

# Update centerlines
mid_x_idx = len(x_cfd) // 2
mid_y_idx = len(y_cfd) // 2
ext_sol["u_centerline"] = ext_sol["u"][:, mid_x_idx]
ext_sol["v_centerline"] = ext_sol["v"][mid_y_idx, :]

print("INFO: Interpolated external result onto cfd_python grid using RectBivariateSpline")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Shape mismatch bug: plot_comparison will fail when grids differ.

After interpolation, ext_sol["u"], ext_sol["v"], ext_sol["p"] are reshaped to match cfd_python grid dimensions. However, plot_comparison (lines 247-263, 278, 291) still uses ext_solver.X, ext_solver.Y, ext_solver.x, ext_solver.y for plotting these interpolated arrays:

  • Line 247: contourf(ext_solver.X, ext_solver.Y, U_mag_ext) — shape mismatch
  • Line 278: plot(ext_sol["u_centerline"], ext_solver.y) — length mismatch
  • Line 291: plot(ext_solver.x, ext_sol["v_centerline"]) — length mismatch

This will raise a runtime error when the grid sizes differ.

🐛 Proposed fix: pass interpolated coordinates or skip external field plots when interpolated

One approach is to track whether interpolation occurred and use the appropriate coordinates:

     if cfd_python_result["u"].shape != ext_sol["u"].shape:
         print(f"WARN: Grid size mismatch: cfd_python {cfd_python_result['u'].shape} vs external {ext_sol['u'].shape}")

         # Interpolate external result onto cfd_python grid
         x_ext = ext_solver.x
         y_ext = ext_solver.y
         x_cfd = cfd_python_result["x"]
         y_cfd = cfd_python_result["y"]

         u_spline = RectBivariateSpline(y_ext, x_ext, ext_sol["u"])
         v_spline = RectBivariateSpline(y_ext, x_ext, ext_sol["v"])
         p_spline = RectBivariateSpline(y_ext, x_ext, ext_sol["p"])

         ext_sol["u"] = u_spline(y_cfd, x_cfd)
         ext_sol["v"] = v_spline(y_cfd, x_cfd)
         ext_sol["p"] = p_spline(y_cfd, x_cfd)

         # Update centerlines
         mid_x_idx = len(x_cfd) // 2
         mid_y_idx = len(y_cfd) // 2
         ext_sol["u_centerline"] = ext_sol["u"][:, mid_x_idx]
         ext_sol["v_centerline"] = ext_sol["v"][mid_y_idx, :]
+
+        # Store interpolated grid coordinates for plotting
+        ext_sol["_interpolated"] = True
+        ext_sol["_x"] = x_cfd
+        ext_sol["_y"] = y_cfd
+    else:
+        ext_sol["_interpolated"] = False

         print("INFO: Interpolated external result onto cfd_python grid using RectBivariateSpline")

Then update plot_comparison to use these coordinates when ext_sol.get("_interpolated") is True.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@validation/compare_cavity_external.py` around lines 108 - 129, The
interpolated external fields (ext_sol["u"], ext_sol["v"], ext_sol["p"]) are
reshaped to the CFD grid but plotting in plot_comparison still uses
ext_solver.X/Y and ext_solver.x/y causing shape/length mismatches; mark when
interpolation happens (e.g., set ext_sol["_interpolated"]=True and store
ext_sol["_x"]=x_cfd and ext_sol["_y"]=y_cfd) and update plot_comparison to, when
ext_sol.get("_interpolated") is True, use ext_sol["_x"] and ext_sol["_y"] (or
cfd_python_result["x"]/["y"]) for contourf(U_mag_ext) and for plotting
centerlines (use ext_sol["u_centerline"] vs ext_sol["_y"] and
ext_sol["v_centerline"] vs ext_sol["_x"]), otherwise fall back to ext_solver.X/Y
and ext_solver.x/y or skip plotting external fields if coordinates are
incompatible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant